import { Component, ChangeDetectorRef, Host, ChangeDetectionStrategy, Input, OnInit, ViewChild, ElementRef } from "@angular/core";
import { ControversyEventIndicatorModel } from "../../../../../../shared/models/qualitativePerformance.model";
import { IncidentCategory } from "../../../../../../shared/models/incidentCategory.enum";
import { environment } from "../../../../../../../environments/environment";
import { CompanyControversiesService } from "../../companyControversies.service";
import { LocationModel } from "../../../../../../shared/models/location.model";
import { IncidentDetailsModel, GroupedIncidentsModel } from "../../models/incidentDetails.model";
import { BaseComponent } from "../../../../../../shared/components/baseComponent/base.component";
import { ModalComponent } from "../../../../../../shared/components/modal/modal.component";
import { NgxSmartModalService } from "ngx-smart-modal";
import * as moment from 'moment';
import * as _ from 'lodash';

/**
 * Controversy event indicator component
 *
 * Author: Sorin Spiru
 * Date: 14.03.2018
 */
@Component({
    moduleId: module.id,
    selector: 'controversy-indicator',
    templateUrl: 'controversiesEventIndicator.component.html',
    styleUrls: [
        '../../../company.component.scss',
        '../../companyControversies.component.scss'
    ],
    changeDetection: ChangeDetectionStrategy.Default
})
export class ControversiesEventIndicatorComponent extends BaseComponent implements OnInit {
    public incidentCategory: typeof IncidentCategory = IncidentCategory;
    public readonly resourcesUrl: string = environment.resourcesUrl;
    public expanded: boolean = false;
    public eventLocation: string;
    public eventTags: string;
    public incidentLocations: LocationModel[];
    public indicatorDetails: ControversyEventIndicatorModel;
    public oldestIncidentDate: string;
    public incidents: GroupedIncidentsModel[];
    public impactData = [];
    public hasMainIncidents: boolean = false;
    public selectedIncident: IncidentDetailsModel = undefined;
    public selectedMainIncident: IncidentDetailsModel = undefined;

    @ViewChild('panelLink') panelLink: ElementRef;

    @ViewChild('controversyIndicatorDetails') controversyIndicatorDetails: ModalComponent;

    @Input() companyId: string;

    @Input() indicatorIndex: number;

    @Input() indicator: ControversyEventIndicatorModel;

    @Input() noExpand: boolean;

    constructor(private companyControversiesService: CompanyControversiesService,
        private ngxSmartModalService: NgxSmartModalService,
        private cdRef: ChangeDetectorRef) {
        super(cdRef);
    }

    ngOnInit() {
        window.scrollTo(0, 0);
    }

    public clickToToggle(): void {
        if (this.noExpand !== true) {
            this.panelLink.nativeElement.click();
        }
    }

    public collapseToggle(): void {
        this.expanded = !this.expanded;
        if (this.expanded && this.indicatorDetails == undefined) {
            //get details
            this.companyControversiesService.getEventIndicator(this.companyId, this.indicator.id).subscribe((data) => {
                this.indicatorDetails = data;
                this.cdRef.markForCheck();
            }, error => this.errorCallback(_ => { this.indicatorDetails = undefined; }, error));

            //get locations
            this.companyControversiesService.getIncidentLocations(this.companyId, this.indicator.baseEventIndicatorId).subscribe(data => {
                this.incidentLocations = data.map(function (o) { return o.geoData; });
                this.eventLocation = this.incidentLocations.map(function (o) { return o.address; }).join(', ');
                this.cdRef.markForCheck();
            }, error => this.errorCallback(_ => { this.incidentLocations = undefined; this.eventLocation = undefined; }, error));

            //get event indicator incidents
            this.companyControversiesService.getIncidents(this.companyId, this.indicator.baseEventIndicatorId).subscribe(data => {
                //group incidents by initial incident
                this.incidents = _(data as any[]).groupBy('incidentId').map(function (items, key) {
                    return { key, main: items.length == 1 ? items[0] : items.find(x => x.type == 0), updates: items.length > 1 ? items.filter(x => x.type != 0) : [] };
                }).value();
                this.impactData = [];
                let incidentId = undefined;
                data.forEach(incident => {
                    this.hasMainIncidents = this.hasMainIncidents || incident.isMainIncident;
                    const isMainIncident = incident.isMainIncident && incident.incidentId !== incidentId;
                    this.impactData.push(
                        {
                            X: moment(incident.incidentDate).format('YYYY-MM-DD'),
                            Y: Math.max(incident.riskScore, incident.impactScore),
                            name: incident.name,
                            isMain: isMainIncident,
                            color: isMainIncident ? 'orange' : 'black'
                        }
                    );
                    incidentId = incident.incidentId;
                });

                //ordered descending
                if (this.impactData.length > 0) {
                    this.oldestIncidentDate = this.impactData[this.impactData.length - 1].X;
                }

                this.eventTags = Array.from(new Set(data.map(function (o) { return o.mainTag; }))).join(', ');
                this.cdRef.markForCheck();
            }, error => this.errorCallback(_ => { this.incidents = undefined; this.eventTags = undefined; }, error));
        }
    }

    get indicatorCode() {
        return this.indicator.id.split('-').join('_');
    }

    public showDetails(id: string, incident: IncidentDetailsModel) {
        this.selectedIncident = incident;
        if (this.selectedIncident.type != 0)
            this.selectedMainIncident = this.incidents.find(x => x.key == incident.incidentId).main;
        this.ngxSmartModalService.getModal(id + '_incident').open();
    }
}
